// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-09-23  Jed Young  Creation
//

using fwt
using gfx
using chunmapView
using chunmapDesktop

class LayerPane : Pane
{
  MapCanvas mapCanvas
  Layer? curLayer
  AttrTable attrTable := AttrTable()

  new make(MapCanvas mapCanvas)
  {
    this.mapCanvas = mapCanvas
    rebind
  }

  Void rebind()
  {
    removeAll
    mapCanvas.layers.eachr |lyr|
    {
      item := Button
      {
        text = lyr.name; mode = ButtonMode.check; selected = lyr.isVisible
        onAction.add { lyr.isVisible = !lyr.isVisible; mapCanvas.renderMap }
        it.onMouseUp.add |e| { curLayer = lyr; if (e.button == 3) this.popup(false, e) }
      }
      this.add(item)
    }
    relayout
  }

  Void popup(Bool withPos, Event event)
  {
    makePopup.open(event.widget, withPos ? Point.make(0, event.widget.size.h) : event.pos)
  }

  Menu makePopup()
  {
    return Menu
    {
      MenuItem
      {
        text = "toTop"; onAction.add |e|
        {
          mapCanvas.layers.moveTo(curLayer, mapCanvas.layers.size-1)
          rebind
          mapCanvas.renderMap
        }
      },
      MenuItem
      {
        text = "toUp"; onAction.add |e|
        {
          mapCanvas.layers.moveTo(curLayer, mapCanvas.layers.index(curLayer)+1)
          rebind
          mapCanvas.renderMap
        }
      },
      MenuItem
      {
        text = "toDown"; onAction.add |e|
        {
          mapCanvas.layers.moveTo(curLayer, mapCanvas.layers.index(curLayer)-1)
          rebind
          mapCanvas.renderMap
        }
      },
      MenuItem
      {
        text = "toBottom"; onAction.add |e|
        {
          mapCanvas.layers.moveTo(curLayer, 0)
          rebind
          mapCanvas.renderMap
        }
      },
      MenuItem { text = "remove"; onAction.add |e|{ mapCanvas.layers.remove(curLayer); rebind; mapCanvas.renderMap } },;

      addSep
      MenuItem { text = "attrTable"; onAction.add |e|{  attrTable.show(curLayer) } },
      MenuItem { text = "style"; onAction.add |e|{ if(StyleDlg.show(mapCanvas.window, curLayer)) mapCanvas.renderMap } },
    }
  }

  override Void onLayout()
  {
    Int y := 10
    children.each |item|
    {
      item.pack
      item.pos = Point(0, y)
      y += item.size.h
    }
  }

  override Size prefSize(Hints hints := Hints.defVal)
  {
    Int h := 50
    Int w := 100

    children.each
    {
      h = h.max(it.prefSize.h)
      w = w.max(it.prefSize.w)
    }
    return Size(w, h)
  }
}